package com.example.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author: dangwen
 * @createDate: 2021/3/13
 */
public class SelfThreadPool {
    private static final int WORK_COUNT = 5;
    private static final int DEFAULT_SIZE = 10;

    private int pool_size;
    private final BlockingQueue<Runnable> taskQueue;
    private final int work_number;
    private WorkThread[] workThreads;

    public SelfThreadPool(int pool_size, int work_number){
        this.pool_size = pool_size <= 0 ? DEFAULT_SIZE : pool_size;
        this.work_number = work_number <= 0 ? WORK_COUNT : work_number;
        workThreads = new WorkThread[work_number];
        taskQueue = new ArrayBlockingQueue<>(pool_size);

        for (int i = 0; i < workThreads.length; i++) {
            workThreads[i] = new WorkThread();
            workThreads[i].start();
        }

    }
    class WorkThread extends Thread{
        @Override
        public void run() {
            Runnable take = null;
            try {
                while(!isInterrupted()){
                    take = taskQueue.take();
//                    Thread.sleep(1000);
//                    System.out.println(" WorkThread " + getName() + " is excute..");
                    take.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void stopWorker() {
            interrupt();
        }
    }

    public void destroy(){
        System.out.println("destroy thread pool ...");
        for (int i = 0; i < workThreads.length; i++) {
            workThreads[i].stopWorker();
            workThreads[i] = null;
        }
        taskQueue.clear();
    }

    public void execute(Runnable task){
        try {
            taskQueue.put(task);
            System.out.println("当前队列的长度为："+taskQueue.size());;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
